package com.example.hetong_system.controller;

import com.example.hetong_system.model.*;
import com.example.hetong_system.model.dto.*;
import com.example.hetong_system.repository.DocumentRepository;
import com.example.hetong_system.service.AIService;
import com.example.hetong_system.service.ClauseService;
import com.example.hetong_system.service.ContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/auth")
public class ContractController {

    @Autowired
    private ContractService contractService;

    @Autowired
    private ClauseService clauseService;

    @Autowired
    private AIService aiService;

    // 现有方法：创建合同
    @PostMapping("/contracts")
    public ResponseEntity<Contract> createContract(@RequestBody Contract contract) {
        Contract savedContract = contractService.save(contract);
        return ResponseEntity.ok(savedContract);
    }

    // 现有方法：根据ID获取合同
    @GetMapping("/contracts/{id}")
    public ResponseEntity<Contract> getContract(@PathVariable Long id) {
        Optional<Contract> contract = contractService.findById(id);
        return contract.map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    // 现有方法：根据状态获取合同（返回DTO列表）
    @GetMapping
    public ResponseEntity<List<ContractDTO>> getContractsByStatus(@RequestParam String status) {
        List<ContractDTO> contracts = contractService.findByStatusAsDTO(status);
        return ResponseEntity.ok(contracts);
    }

    // 新增方法：根据项目经理ID获取合同
    @GetMapping("/manager/{managerId}")
    public ResponseEntity<List<Contract>> getContractsByManager(@PathVariable Long managerId) {
        List<Contract> contracts = contractService.findByProjectManagerId(managerId);
        return ResponseEntity.ok(contracts);
    }

    // 新增方法：根据客户ID获取合同
    @GetMapping("/customer/{customerId}")
    public ResponseEntity<List<Contract>> getContractsByCustomer(@PathVariable Long customerId) {
        List<Contract> contracts = contractService.findByCustomerId(customerId);
        return ResponseEntity.ok(contracts);
    }

    // 新增方法：创建合同（带条款管理）
    @PostMapping("/create-with-clauses")
    public ResponseEntity<Contract> createContractWithClauses(
            @RequestParam Long projectManagerId,
            @RequestParam String contractName,
            @RequestParam Long customerId,
            @RequestParam(required = false) List<Long> existingClauseIds,
            @RequestParam(required = false) List<String> newClauseContents) {

        Contract contract = contractService.createContractWithClauses(
                projectManagerId, contractName, customerId, existingClauseIds, newClauseContents);

        return ResponseEntity.ok(contract);
    }

    /**
     * 获取待提交合同数量
     */
    @GetMapping("/contracts/pending-submit/count")
    public ResponseEntity<Long> getPendingSubmitContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 权限检查：只有项目经理可以查看
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getPendingSubmitContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            // 记录异常日志
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    /**
     * 获取待修订合同数量
     */
    @GetMapping("/contracts/pending-revision/count")
    public ResponseEntity<Long> getPendingRevisionContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 权限检查：只有项目经理可以查看
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getPendingRevisionContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    /**
     * 获取已完成合同数量
     */
    @GetMapping("/contracts/completed/count")
    public ResponseEntity<Long> getCompletedContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId) {
        try {
            Long count = contractService.getCompletedContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    /**
     * 获取待提交合同列表（带分页）
     */
    @GetMapping("/contracts/pending-submit")
    public ResponseEntity<PageResponse<ContractDTO>> getPendingSubmitContracts(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @PageableDefault(size = 10) Pageable pageable) {

        // 权限检查：只有项目经理可以查看
        if (!"PROJECT_MANAGER".equals(position)) {
            return ResponseEntity.status(403).body(null);
        }

        Page<ContractDTO> contracts = contractService.getPendingSubmitContracts(employeeId, pageable);
        return ResponseEntity.ok(PageResponse.of(contracts));
    }

    /**
     * 获取待修订合同列表（带分页）
     */
    @GetMapping("/contracts/pending-revision")
    public ResponseEntity<PageResponse<ContractDTO>> getPendingRevisionContracts(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @PageableDefault(size = 10) Pageable pageable) {

        // 权限检查：只有项目经理可以查看
        if (!"PROJECT_MANAGER".equals(position)) {
            return ResponseEntity.status(403).body(null);
        }

        Page<ContractDTO> contracts = contractService.getPendingRevisionContracts(employeeId, pageable);
        return ResponseEntity.ok(PageResponse.of(contracts));
    }

    /**
     * 提交合同进行审核
     */
    @PutMapping("/contracts/{id}/submit-review")
    public ResponseEntity<Void> submitContractForReview(
            @PathVariable Long id,
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {

        // 权限检查：只有项目经理可以提交
        if (!"PROJECT_MANAGER".equals(position)) {
            return ResponseEntity.status(403).build();
        }

        contractService.submitContractForReview(id, employeeId);
        return ResponseEntity.noContent().build();
    }

    /**
     * 获取待审核合同数量
     */
    @GetMapping("/contracts/pending-audit/count")
    public ResponseEntity<Long> getPendingAuditContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 权限检查：只有法务或财务专员可以查看
            if (!"LEGAL_SPECIALIST".equals(position) && !"FINANCE_SPECIALIST".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getPendingAuditContractCount(employeeId, position);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    /**
     * 获取待审核合同列表（带分页）
     */
    @GetMapping("/contracts/pending-audit")
    public ResponseEntity<PageResponse<Contract>> getPendingAuditContracts(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @RequestParam String type, // legal或finance
            @PageableDefault(size = 10) Pageable pageable) {

        // 权限检查：只有法务或财务专员可以查看
        if (!"LEGAL_SPECIALIST".equals(position) && !"FINANCE_SPECIALIST".equals(position)) {
            return ResponseEntity.status(403).body(null);
        }

        Page<Contract> contracts = contractService.getPendingAuditContracts(employeeId, position, type, pageable);
        return ResponseEntity.ok(PageResponse.of(contracts));
    }

    /**
     * 获取合同审核详情
     */
    @GetMapping("/contracts/{contractId}/audit")
    public ResponseEntity<ContractAuditDTO> getContractForAudit(
            @PathVariable Long contractId,
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @RequestParam String type) {

        // 权限检查：只有对应角色可以查看
        if (("LEGAL_SPECIALIST".equals(position) && !"legal".equals(type)) ||
                ("FINANCE_SPECIALIST".equals(position) && !"finance".equals(type))) {
            return ResponseEntity.status(403).body(null);
        }

        ContractAuditDTO contractAuditDTO = contractService.getContractForAudit(contractId, type);
        return ResponseEntity.ok(contractAuditDTO);
    }

    /**
     * 获取条款审核详情
     */
    @GetMapping("/contracts/{contractId}/clauses/{clauseId}/audit")
    public ResponseEntity<ContractClauseAuditDTO> getClauseForAudit(
            @PathVariable Long contractId,
            @PathVariable Long clauseId,
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @RequestParam String type) {

        // 权限检查：只有对应角色可以查看
        if (("LEGAL_SPECIALIST".equals(position) && !"legal".equals(type)) ||
                ("FINANCE_SPECIALIST".equals(position) && !"finance".equals(type))) {
            return ResponseEntity.status(403).body(null);
        }

        try {
            ContractClauseAuditDTO clauseAuditDTO = contractService.getClauseForAudit(contractId, clauseId, type);
            return ResponseEntity.ok(clauseAuditDTO);
        } catch (IllegalArgumentException e) {
            // 处理参数异常（如合同或条款不存在）
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            // 处理其他异常
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 提交条款审核
     */
    @PutMapping("/contracts/{contractId}/clauses/{clauseId}/audit")
    public ResponseEntity<Void> submitClauseAudit(
            @PathVariable Long contractId,
            @PathVariable Long clauseId,
            @RequestBody ContractClauseAuditDTO auditDTO,
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {

        // 权限检查：只有对应角色可以提交审核
        if (("LEGAL_SPECIALIST".equals(position) && !"legal".equals(auditDTO.getType())) ||
                ("FINANCE_SPECIALIST".equals(position) && !"finance".equals(auditDTO.getType()))) {
            return ResponseEntity.status(403).build();
        }

        contractService.submitClauseAudit(contractId, clauseId, auditDTO, employeeId);
        return ResponseEntity.noContent().build();
    }

    /**
     * 获取待客户审核的合同列表
     */
    @GetMapping("/contracts/pending-customer-audit")
    public ResponseEntity<Page<Contract>> getPendingCustomerAuditContracts(
            @RequestHeader("X-Customer-Id") Long customerId,
            Pageable pageable) {
        Page<Contract> contracts = contractService.getPendingCustomerAuditContracts(customerId, pageable);
        return ResponseEntity.ok(contracts);
    }

    /**
     * 获取合同客户审核详情
     */
    @GetMapping("/contracts/{contractId}/customer-audit")
    public ResponseEntity<ContractCustomerAuditDTO> getContractForCustomerAudit(
            @PathVariable Long contractId) {
        ContractCustomerAuditDTO auditDTO = contractService.getContractForCustomerAudit(contractId);
        return ResponseEntity.ok(auditDTO);
    }

    /**
     * 获取条款客户审核详情
     */
    @GetMapping("/contracts/{contractId}/clauses/{clauseId}/customer-audit")
    public ResponseEntity<ContractClauseAuditDTO> getClauseForCustomerAudit(
            @PathVariable Long contractId,
            @PathVariable Long clauseId) {
        ContractClauseAuditDTO clauseDTO = contractService.getClauseForCustomerAudit(contractId, clauseId);
        return ResponseEntity.ok(clauseDTO);
    }

    /**
     * 提交条款客户审核
     */
    @PostMapping("/contracts/{contractId}/clauses/{clauseId}/customer-audit")
    public ResponseEntity<Void> submitCustomerClauseAudit(
            @PathVariable Long contractId,
            @PathVariable Long clauseId,
            @RequestBody ContractClauseAuditDTO auditDTO,
            @RequestHeader("X-Customer-Id") Long customerId) {
        contractService.submitCustomerClauseAudit(contractId, clauseId, auditDTO, customerId);
        return ResponseEntity.ok().build();
    }

    // 获取条款详情（包括审核状态和意见）
    @GetMapping("/clauses/{clauseId}/contract/{contractId}")
    public ResponseEntity<ClauseDetailDTO> getClauseDetail(
            @PathVariable Long contractId,
            @PathVariable Long clauseId) {
        ClauseDetailDTO clauseDetail = clauseService.getClauseDetail(contractId, clauseId);
        return ResponseEntity.ok(clauseDetail);
    }

    // 根据客户ID获取合同（带分页）
    @GetMapping("/contracts/customer/{customerId}")
    public ResponseEntity<PageResponse<Contract>> getContractsByCustomer(
            @PathVariable Long customerId,
            @PageableDefault(size = 10) Pageable pageable) {

        Page<Contract> contracts = contractService.findByCustomerId(customerId, pageable);
        return ResponseEntity.ok(PageResponse.of(contracts));
    }

    // 获取指定项目经理的所有合同（带分页）
    @GetMapping("/manager/{managerId}/contracts")
    public ResponseEntity<Page<Contract>> getContractsByManager(
            @PathVariable Long managerId,
            @PageableDefault(size = 10) Pageable pageable) {
        Page<Contract> contracts = contractService.getContractsByManagerId(managerId, pageable);
        return ResponseEntity.ok(contracts);
    }

    private static final String FILE_STORAGE_DIR = "D:/LUT/Web_Project/Hetong_System/src/main/java/cangku/";

    /**
     * 获取待签订合同列表
     * 修复：添加请求头权限校验，使用正确的参数传递方式
     */
    @GetMapping("/contracts/pending-sign/{managerId}")
    public ResponseEntity<List<Contract>> getPendingSignContracts(
            @PathVariable Long managerId,
            @RequestHeader("X-Employee-Position") String position,
            @RequestParam(value = "page", required = false, defaultValue = "0") int page,
            @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        try {
            // 参数验证
            if (page < 0 || size <= 0) {
                return ResponseEntity.badRequest().body(null);
            }

            // 权限检查：只有项目经理可以访问
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(null);
            }

            List<Contract> contracts = contractService.getPendingSignContracts(managerId, page, size);
            return ResponseEntity.ok(contracts);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取待签订合同数量
     * 修复：使用正确的请求头参数名称
     */
    @GetMapping("/contracts/pending-sign/count")
    public ResponseEntity<Long> getPendingSignContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 参数验证
            if (employeeId == null) {
                return ResponseEntity.badRequest().body(0L);
            }

            // 权限检查：只有项目经理可以访问
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getPendingSignContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(0L);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    // 下载合同PDF
    @GetMapping("/contracts/{id}/pdf")
    public ResponseEntity<byte[]> downloadContractPdf(@PathVariable Long id, HttpServletResponse response)
            throws IOException {
        byte[] pdfData = contractService.generateContractPdf(id);

        response.setContentType("application/pdf");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"contract_" + id + ".pdf\"");
        response.getOutputStream().write(pdfData);
        response.getOutputStream().flush();

        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdfData);
    }

    @Autowired
    private DocumentRepository documentRepository;


    // 新增：通过合同ID从document表查询并下载PDF
    @GetMapping("/documents/contracts/{contractId}/pdf")
    public void downloadContractFromDocument(
            @PathVariable Long contractId,
            HttpServletResponse response) throws IOException {

        // 1. 根据合同ID查询document表（只查类型为“签订合同”的文档，type=233）
        // （参考你的业务：type=233表示签订合同的PDF，对应Document表的type字段）
        Optional<Document> documentOpt = documentRepository.findByContractIdAndType(contractId, 233);
        if (!documentOpt.isPresent()) {
            // 文件不存在时返回404
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到合同对应的PDF文件");
            return;
        }

        // 2. 获取文件存储路径（从document表的file_path字段）
        Document document = documentOpt.get();
        String filePath = document.getFilePath();
        File pdfFile = new File(filePath);

        // 3. 验证文件是否存在
        if (!pdfFile.exists() || !pdfFile.isFile()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "PDF文件已被删除或移动");
            return;
        }

        // 4. 设置响应头（告诉浏览器下载文件）
        response.setContentType("application/pdf");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + pdfFile.getName() + "\"");
        response.setContentLengthLong(pdfFile.length());

        // 5. 读取文件并写入响应流
        try (InputStream in = new FileInputStream(pdfFile);
             OutputStream out = response.getOutputStream()) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            out.flush(); // 确保所有数据发送到前端
        } catch (IOException e) {
            // 处理文件读取异常
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文件读取失败");
            e.printStackTrace();
        }
    }

    // 确认签订合同
    @PostMapping("/contracts/{id}/sign")
    public ResponseEntity<Void> signContract(@PathVariable Long id, @RequestParam("file") MultipartFile file)
            throws IOException {
        try {
            contractService.signContract(id, file);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 获取待客户确认的合同列表（带分页）
     */
    @GetMapping("/contracts/pending-confirm/{customerId}")
    public ResponseEntity<List<Contract>> getPendingConfirmContracts(
            @PathVariable Long customerId,
            @RequestParam(value = "page", required = false, defaultValue = "0") int page,
            @RequestParam(value = "size", required = false, defaultValue = "10") int size) {
        try {
            // 参数验证
            if (page < 0 || size <= 0) {
                return ResponseEntity.badRequest().body(null);
            }

            List<Contract> contracts = contractService.getPendingConfirmContracts(customerId, page, size);
            return ResponseEntity.ok(contracts);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取待客户确认的合同详情
     */
    @GetMapping("/contracts/{id}/customer-confirm")
    public ResponseEntity<Contract> getContractForCustomerConfirmation(@PathVariable Long id) {
        try {
            Contract contract = contractService.getContractForCustomerConfirmation(id);
            return ResponseEntity.ok(contract);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 客户确认合同
     */
    @PutMapping("/contracts/{id}/confirm")
    public ResponseEntity<Void> confirmContractByCustomer(@PathVariable Long id) {
        try {
            contractService.confirmContractByCustomer(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    @GetMapping("/contracts/ongoing/count")
    public ResponseEntity<Long> getOngoingContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 权限检查：只有项目经理可以查看
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getOngoingContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

//    /**
//     * 获取进行中的合同列表（带分页）
//     */
//    @GetMapping("/contracts/ongoing/{managerId}")
//    public ResponseEntity<Page<Contract>> getOngoingContracts(
//            @PathVariable Long managerId,
//            @RequestHeader("X-Employee-Position") String position,
//            @PageableDefault(size = 10) Pageable pageable) {
//        try {
//            // 权限检查：只有项目经理可以访问
//            if (!"PROJECT_MANAGER".equals(position)) {
//                return ResponseEntity.status(403).body(null);
//            }
//
//            Page<Contract> contracts = contractService.getOngoingContracts(managerId, pageable);
//            return ResponseEntity.ok(contracts);
//        } catch (IllegalArgumentException e) {
//            return ResponseEntity.badRequest().body(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(500).body(null);
//        }
//    }

    /**
     * 获取合同进度详情
     */
    @GetMapping("/contracts/{id}/progress")
    public ResponseEntity<ContractProgressDTO> getContractProgress(@PathVariable Long id) {
        try {
            ContractProgressDTO progressDTO = contractService.getContractProgress(id);
            return ResponseEntity.ok(progressDTO);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 开始履行合同
     */
    @PutMapping("/contracts/{id}/start-execution")
    public ResponseEntity<Void> startContractExecution(@PathVariable Long id) {
        try {
            contractService.startContractExecution(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 更新定金阶段描述
     */
    @PutMapping("/contracts/{id}/update-deposit")
    public ResponseEntity<Void> updateDepositDescription(
            @PathVariable Long id, @RequestBody String description) {
        try {
            contractService.updateDepositDescription(id, description);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 更新执行阶段描述
     */
    @PutMapping("/contracts/{id}/update-execution")
    public ResponseEntity<Void> updateExecutionDescription(
            @PathVariable Long id, @RequestBody String description) {
        try {
            contractService.updateExecutionDescription(id, description);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }

    /**
     * 确认归档合同
     */
    @PutMapping("/contracts/{id}/archive")
    public ResponseEntity<Void> archiveContract(@PathVariable Long id) {
        try {
            contractService.archiveContract(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }


    /**
     * 获取进行中的合同列表（带分页）
     */
    @GetMapping("/contracts/ongoing/{managerId}")
    public ResponseEntity<Page<Contract>> getOngoingContracts(
            @PathVariable Long managerId,
            @RequestHeader("X-Employee-Position") String position,
            @PageableDefault(size = 10) Pageable pageable) {
        try {
            // 权限检查
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(null);
            }

            Page<Contract> contracts = contractService.getOngoingContracts(managerId, pageable);
            return ResponseEntity.ok(contracts);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取顾客进行中的合同列表（带分页）
     */
    @GetMapping("/contracts/customer-ongoing/{customerId}")
    public ResponseEntity<Page<Contract>> getCustomerOngoingContracts(
            @PathVariable Long customerId,
            @PageableDefault(size = 10) Pageable pageable) {
        try {
            Page<Contract> contracts = contractService.getCustomerOngoingContracts(customerId, pageable);
            return ResponseEntity.ok(contracts);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取顾客合同进度详情
     */
//    @GetMapping("/contracts/{id}/customer-progress")
//    public ResponseEntity<ContractProgressDTO> getCustomerContractProgress(@PathVariable Long id) {
//        try {
//            ContractProgressDTO progressDTO = contractService.getCustomerContractProgress(id);
//            return ResponseEntity.ok(progressDTO);
//        } catch (IllegalArgumentException e) {
//            return ResponseEntity.badRequest().body(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(500).body(null);
//        }
//    }

    /**
     * 更新顾客合同进度
     */
    @PutMapping("/contracts/{id}/customer/next-stage")
    public ResponseEntity<Void> updateCustomerContractStage(@PathVariable Long id, @RequestBody Map<String, Integer> status) {
        try {
            contractService.updateCustomerContractStage(id, status.get("status"));
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }





    /**
     * 获取顾客已归档的合同列表（带分页）
     */
    @GetMapping("/contracts/customer-archived/{customerId}")
    public ResponseEntity<PageResponse<Contract>> getCustomerArchivedContracts(
            @PathVariable Long customerId,
            @PageableDefault(size = 10) Pageable pageable) {

        Page<Contract> contracts = contractService.findCustomerArchivedContracts(customerId, pageable);
        return ResponseEntity.ok(PageResponse.of(contracts));
    }

    /**
     * 获取里程碑计划详情
     */
    @GetMapping("/milestone-plan/contract/{contractId}")
    public ResponseEntity<MilestonePlan> getMilestonePlanByContractId(@PathVariable Long contractId) {
        MilestonePlan milestonePlan = contractService.getMilestonePlanByContractId(contractId);
        return ResponseEntity.ok(milestonePlan);
    }

    /**
     * 获取项目经理已归档的合同数量
     */
    @GetMapping("/contracts/archived/count")
    public ResponseEntity<Long> getArchivedContractCount(
            @RequestHeader("X-Employee-Id") Long employeeId,
            @RequestHeader("X-Employee-Position") String position) {
        try {
            // 权限检查：只有项目经理可以查看
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(0L);
            }

            Long count = contractService.getArchivedContractCount(employeeId);
            return ResponseEntity.ok(count);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(0L);
        }
    }

    /**
     * 获取项目经理已归档的合同列表（带分页）
     */
    @GetMapping("/contracts/employee-archived/{employeeId}")
    public ResponseEntity<PageResponse<Contract>> getEmployeeArchivedContracts(
            @PathVariable Long employeeId,
            @RequestHeader("X-Employee-Position") String position,
            @PageableDefault(size = 10) Pageable pageable) {

        try {
            // 权限检查：只有项目经理可以访问
            if (!"PROJECT_MANAGER".equals(position)) {
                return ResponseEntity.status(403).body(null);
            }

            Page<Contract> contracts = contractService.getEmployeeArchivedContracts(employeeId, pageable);
            return ResponseEntity.ok(PageResponse.of(contracts));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }


//    /**
//     * 顾客确认完成合同
//     */
//    @PutMapping("/contracts/{id}/customer/complete")
//    public ResponseEntity<Void> completeContractByCustomer(@PathVariable Long id) {
//        try {
//            contractService.completeContractByCustomer(id);
//            return ResponseEntity.noContent().build();
//        } catch (IllegalArgumentException e) {
//            return ResponseEntity.badRequest().body(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(500).body(null);
//        }
//    }


    /**
     * 获取顾客合同进度详情（修复400错误）
     */
    @GetMapping("/contracts/{id}/customer-progress")
    public ResponseEntity<ContractProgressDTO> getCustomerContractProgress(@PathVariable Long id) {
        try {
            // 确保合同ID有效
            if (id == null || id <= 0) {
                return ResponseEntity.badRequest().build();
            }

            ContractProgressDTO progressDTO = contractService.getCustomerContractProgress(id);
            return ResponseEntity.ok(progressDTO);
        } catch (IllegalArgumentException e) {
            // 处理业务异常（如合同不存在）
            return ResponseEntity.badRequest().body(null);
        } catch (Exception e) {
            // 处理系统异常
            e.printStackTrace();
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 顾客确认完成合同（确保接口存在）
     */
    @PutMapping("/contracts/{id}/customer/complete")
    public ResponseEntity<Void> completeContractByCustomer(@PathVariable Long id) {
        try {
            contractService.completeContractByCustomer(id);
            return ResponseEntity.noContent().build();
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).build();
        }
    }






    /**
     * AI助手查询接口
     */
    @PostMapping("/ai/query")
    public AIResponse query(@RequestBody Map<String, Object> request) {
        String query = (String) request.get("query");
        Long contractId = request.containsKey("contractId") ?
                Long.valueOf(request.get("contractId").toString()) : null;

        // 调用AI服务获取回答
        String answer = aiService.getAnswer(query, contractId);

        // 返回结果
        return new AIResponse(answer);
    }







}